package com.code.app.activity;

import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.webkit.WebView;
import android.widget.EditText;

import com.code.app.R;
import com.code.app.base.BaseActivity;
import com.code.app.core.IJavaScriptInterface;
import com.code.app.core.JavaScriptInterfaceImpl;

public class WebViewActivity extends BaseActivity implements IJavaScriptInterface {

    private WebView webView;

    private EditText editContent;

    private Handler handler;

    private JavaScriptInterfaceImpl javaScriptInterface;

    @Override
    public int getLayoutId() {
        return R.layout.activity_webview;
    }

    @Override
    public void initFunction(Bundle savedInstanceState) {
        webView = findViewById(R.id.web);
        editContent = findViewById(R.id.edit_input);

        // 是否支持viewport属性，默认值 false
        // 页面通过`<meta name="viewport" ... />`自适应手机屏幕
        // 当值为true且viewport标签不存在或未指定宽度时使用 wide viewport mode
        webView.getSettings().setUseWideViewPort(true);
        // 是否使用overview mode加载页面，默认值 false
        // 当页面宽度大于WebView宽度时，缩小使页面宽度等于WebView宽度
        webView.getSettings().setLoadWithOverviewMode(true);
        handler = new Handler();
        javaScriptInterface = new JavaScriptInterfaceImpl();
        javaScriptInterface.setHandler(handler);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.addJavascriptInterface(javaScriptInterface, "javaScriptInterface");
        //chrome://inspect/#devices API19以上
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            webView.setWebContentsDebuggingEnabled(true);
        }
        webView.loadUrl("file:///android_asset/index.html");
    }

    public void onClick(View view) {
        String text = editContent.getText().toString();
        if (!TextUtils.isEmpty(text)) {
            webView.loadUrl("javascript:if(window.remot){window.remote('" + text + "');}");
            webView.loadUrl("javascript:if(window.remot){window.remote(\"" + text + "\");}");
        }

    }



    @Override
    protected void onPause() {
        super.onPause();
        webView.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        webView.onResume();
    }

    @Override
    public void setValue(String msg) {
        editContent.setText(msg);
    }

}
